package com.goa.parse;


import com.goa.entity.DeviceResult;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 01 04 0c 001c0016002508ee04ae046a 67e4
 * 数据位数 001c0016002508ee04ae046a
 * 电压电流响应指令
 * 进行分位解析
 */
public class ModbusDataProcessor {

    // 改造后的方法：接收List<DeviceResult>和hexData字符串
    public static Map<String, Integer> processModbusData(byte[]  bytes, List<DeviceResult> deviceResults) {
        // 将16进制字符串转换为字节数组
//        byte[] bytes = hexStringToByteArray(hexData);
        Map<String, Integer> results = new HashMap<>();

        //遍历DeviceResult列表，根据beginByte和endByte解析数据
        for (DeviceResult deviceResult : deviceResults) {
            int beginByte = deviceResult.getBeginByte();
            int endByte = deviceResult.getEndByte();
            String resultColumn = deviceResult.getResultColumn();

            if (beginByte - 1 < bytes.length && endByte <= bytes.length) {
                // 分割数据
                byte[] segment = new byte[endByte - beginByte + 1];
                System.arraycopy(bytes, beginByte - 1, segment, 0, segment.length);
                // 转换为16进制字符串并存入结果
                results.put(resultColumn, Integer.parseInt(bytesToHex(segment),16));
            } else {
                // 可选：记录或处理超出字节数组范围的情况
                System.err.println("Warning: Byte range for " + resultColumn + " is out of bounds.");
            }
        }
        return results;
    }



    private static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                 + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString().toUpperCase();
    }
}
